package com.wh.wisdomsite.xbox.server.controller.ba;

import com.wh.wisdomsite.xbox.ba.entity.Menu;
import com.wh.wisdomsite.xbox.ba.service.IMenuService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.ba.MenuIn;
import com.wh.wisdomsite.xbox.server.manager.MenuMapManager;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.EasyUiIconUtil;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 菜单Controller
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.controller.us
 * @author: 丁奕
 * @date: 2018-08-03 11:55
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/menu")
public class MenuController {

    private static final Log logger = LogFactory.getLog(MenuController.class);

    @Autowired
    private IMenuService iMenuService;

    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:ba_menu_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(){
        return "/ba/menu/menuList";
    }

    /**
     * 获取树形菜单列表
     * @param response
     * @param
     */
    @RequiresPermissions("rules:ba_menu_find")
    @RequestMapping(value = "/getTreeMenu.do")
    public void getTreeMenu(HttpServletResponse response){
        try {
            logger.info("加载树形菜单-->>开始");
            List<Menu> menuList = iMenuService.getTreeMenu();
            JSONArray array = new JSONArray();
            if(menuList.size() > 0){
                for(Menu menu : menuList){
                    JSONObject object = new JSONObject(menu);
                    array.put(object);
                }
            }
            ResManager.getTextOut(response).print(array);
            logger.info("加载树形菜单-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("加载树形菜单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 根据当前登陆的用户获取树形菜单列表
     * @param response
     * @param
     */
    @RequestMapping(value = "/getTreeMenuByUser.do")
    public void getTreeMenuByUser(HttpServletResponse response){
        try {
            logger.info("加载树形菜单-->>开始");
            List<Menu> menuList = null;
            JSONArray array = new JSONArray();
            //超级管理员直接获得所有菜单，非超级管理员只能获取自己所拥有的菜单进行权限分配
            if(UserUtils.isSysAdmin()){
                menuList = iMenuService.getTreeMenu();
            }else{
                menuList = UserUtils.getServerSessionUser().getMenuList();
            }
            if(menuList.size() > 0){
                for(Menu menu : menuList){
                    JSONObject object = new JSONObject(menu);
                    array.put(object);
                }
            }
            ResManager.getTextOut(response).print(array);
            logger.info("加载树形菜单-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("加载树形菜单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 菜单详情
     * @param menuIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:ba_menu_view")
    @RequestMapping("menuDesc.do")
    public String menuDesc(MenuIn menuIn, HttpServletRequest request) {
        try {
            logger.info("菜单详情-->>开始");
            Map<String, Object> menuMap = iMenuService.getMapById(menuIn.getId());
            if(menuMap.get("createBy") != null){
                menuMap.put("createBy", UserMapManager.getUserLoginNameInMap(menuMap.get("createBy").toString()));
            }
            if(menuMap.get("updateBy") != null){
                menuMap.put("updateBy", UserMapManager.getUserLoginNameInMap(menuMap.get("updateBy").toString()));
            }
            request.setAttribute("menu", menuMap);
            logger.info("菜单详情-->>结束");
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return "/ba/menu/menuDesc";
    }

    /**
     * 验证权限标识是否已经存在
     * @param value
     * @param oldValue
     * @return
     */
    @RequestMapping(value = "/permissionIsExists.do", method = RequestMethod.POST)
    public void permissionIsExists(HttpServletResponse response, String value, String oldValue){
        Map<String, Object> map = new HashMap<>();
        map.put("result", iMenuService.permissionIsExists(value, oldValue));
        JSONObject json = new JSONObject(map);
        ResManager.getTextOut(response).print(json);
    }

    /**
     * 跳转至添加或修改页面
     * @return
     */
    @RequestMapping("/toMenuOption")
    public String toMenuOption(String id, HttpServletRequest request){
        try {
            logger.debug("添加修改菜单跳转-->>开始");
            if(StringUtils.isNotEmpty(id)){
                //注入menu参数
                Map<String, Object> menu = iMenuService.getMapById(id);
                request.setAttribute("menu", menu);
            }

            List<String> iconNames = EasyUiIconUtil.getAllIconNames();
            request.setAttribute("iconNames", iconNames);
        }catch (Exception e) {
            logger.error("添加修改菜单跳转-->>Exception : " + e.getMessage());
            e.printStackTrace();
        }
        logger.debug("添加修改菜单跳转-->>结束");
        return "ba/menu/menuOption";
    }

    /**
     * 更新或者修改
     * @param menu
     * @param response
     */
    @RequiresPermissions("rules:ba_menu_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Menu menu,HttpServletResponse response){
        try {
            //判断是否有选择父级菜单，没有则设置为0
            if(menu.getParentId() == null || menu.getParentId() == ""){
                menu.setParentId("0");
            }
            //判断菜单是否已经存在,存在即更新.否则为添加
            if(StringUtils.isNotEmpty(menu.getMeId())){
                logger.info("修改菜单-->>开始");
                menu.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                menu.setUpdateDate(new Date());
                if(org.apache.commons.lang3.StringUtils.isEmpty(menu.getPermission())){
                    menu.setPermission(null);
                }
                iMenuService.updateById(menu);
                logger.info("修改菜单-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("菜单更新成功"));

            }else {
                logger.info("添加菜单-->>开始");
                menu.setCreateBy(UserUtils.getCurrentUser().getUsId());
                menu.setCreateDate(new Date());
                if(menu.getParentId() == null || menu.getParentId() == ""){
                    menu.setParentId("0");
                }
                menu.setMeId(UUID.randomUUID().toString().replace("-",""));
                if(org.apache.commons.lang3.StringUtils.isEmpty(menu.getPermission())){
                    menu.setPermission(null);
                }
                iMenuService.insert(menu);
                logger.info("添加菜单-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("菜单添加成功"));
            }
            //在menuMap中做更新
            MenuMapManager.updateMenuToMap(menu);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("操作菜单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除菜单
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:ba_menu_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除菜单-->>开始");
            iMenuService.deleteById(id);
            logger.info("删除菜单-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("菜单删除成功"));
            //在menuMap中做更新
            MenuMapManager.remove(id);
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除菜单-->>Exception" + e.getMessage());
        }
    }
}
